// stores/blockchain.js
import { defineStore } from 'pinia'
import { ethers } from 'ethers'
import { ref } from 'vue'
import axios from 'axios'

// 假设您有一个智能合约ABI和地址
import CharityPlatformABI from '@/contracts/CharityPlatform.json'
const CONTRACT_ADDRESS = '0x123...' 

export const useBlockchainStore = defineStore('blockchain', () => {
  const provider = ref(null)
  const signer = ref(null)
  const contract = ref(null)
  const account = ref('')
  const isConnected = ref(false)
  
  // 初始化区块链连接
  const init = async () => {
    if (window.ethereum) {
      try {
        // 请求账户访问
        const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' })
        account.value = accounts[0]
        
        // 设置provider和signer
        provider.value = new ethers.BrowserProvider(window.ethereum)
        signer.value = await provider.value.getSigner()
        
        // 初始化合约
        contract.value = new ethers.Contract(
          CONTRACT_ADDRESS,
          CharityPlatformABI,
          signer.value
        )
        
        isConnected.value = true
        
        // 监听账户变化
        window.ethereum.on('accountsChanged', (accounts) => {
          account.value = accounts[0] || ''
          isConnected.value = accounts.length > 0
        })
        
      } catch (error) {
        console.error('初始化区块链连接失败:', error)
        throw error
      }
    } else {
      throw new Error('请安装MetaMask或其他Web3钱包')
    }
  }
  
  // 上传文件到IPFS
  const uploadToIPFS = async (file) => {
    try {
      const formData = new FormData()
      formData.append('file', file)
      
      const response = await axios.post('https://api.pinata.cloud/pinning/pinFileToIPFS', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'pinata_api_key': 'YOUR_PINATA_API_KEY',
          'pinata_secret_api_key': 'YOUR_PINATA_SECRET_KEY'
        }
      })
      
      return response.data.IpfsHash
    } catch (error) {
      console.error('上传到IPFS失败:', error)
      throw error
    }
  }
  
  // 创建新项目
  const createProject = async (name, metadataURI, goal, durationDays) => {
    if (!contract.value) throw new Error('合约未初始化')
    
    try {
      const tx = await contract.value.createProject(
        name,
        metadataURI,
        ethers.parseEther(goal.toString()),
        durationDays * 24 * 60 * 60 // 转换为秒
      )
      
      return tx
    } catch (error) {
      console.error('创建项目失败:', error)
      throw error
    }
  }
  
  // 获取所有项目
  const getAllProjects = async () => {
    if (!contract.value) throw new Error('合约未初始化')
    
    try {
      const projects = await contract.value.getAllProjects()
      
      // 转换项目数据为更友好的格式
      return projects.map(project => ({
        id: project.id.toString(),
        name: project.name,
        metadataURI: project.metadataURI,
        creator: project.creator,
        goal: ethers.formatEther(project.goal),
        raised: ethers.formatEther(project.raised),
        isActive: project.isActive,
        createdAt: new Date(project.createdAt * 1000).toISOString()
      }))
    } catch (error) {
      console.error('获取项目列表失败:', error)
      throw error
    }
  }
  
  // 获取项目详情
  const getProjectDetails = async (projectId) => {
    if (!contract.value) throw new Error('合约未初始化')
    
    try {
      const project = await contract.value.getProject(projectId)
      
      // 获取元数据
      const metadataResponse = await axios.get(project.metadataURI.replace('ipfs://', 'https://ipfs.io/ipfs/'))
      const metadata = metadataResponse.data
      
      return {
        ...project,
        id: projectId,
        goal: ethers.formatEther(project.goal),
        raised: ethers.formatEther(project.raised),
        metadata
      }
    } catch (error) {
      console.error('获取项目详情失败:', error)
      throw error
    }
  }
  
  return {
    provider,
    signer,
    contract,
    account,
    isConnected,
    init,
    uploadToIPFS,
    createProject,
    getAllProjects,
    getProjectDetails
  }
})